package com.qianfeng.smartplatform.config;

//
//                            _ooOoo_  
//                           o8888888o  
//                           88" . "88  
//                           (| -_- |)  
//                            O\ = /O  
//                        ____/`---'\____  
//                      .   ' \\| |// `.  
//                       / \\||| : |||// \  
//                     / _||||| -:- |||||- \  
//                       | | \\\ - /// | |  
//                     | \_| ''\---/'' | |  
//                      \ .-\__ `-` ___/-. /  
//                   ___`. .' /--.--\ `. . __  
//                ."" '< `.___\_<|>_/___.' >'"".  
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//                 \ \ `-. \_ __\ /__ _/ .-` / /  
//         ======`-.____`-.___\_____/___.-`____.-'======  
//                            `=---='  
//  
//         .............................................  
//                  佛祖镇楼                  BUG辟易  
//          佛曰:  
//                  写字楼里写字间，写字间里程序员；  
//                  程序人员写程序，又拿程序换酒钱。  
//                  酒醒只在网上坐，酒醉还来网下眠；  
//                  酒醉酒醒日复日，网上网下年复年。  
//                  但愿老死电脑间，不愿鞠躬老板前；  
//                  奔驰宝马贵者趣，公交自行程序员。  
//                  别人笑我忒疯癫，我笑自己命太贱；  
//  


import com.qianfeng.smartplatform.security.handler.MyAuthenticationFailureHandler;
import com.qianfeng.smartplatform.security.handler.MyAuthenticationSuccessHandler;
import com.qianfeng.smartplatform.security.handler.MyLogoutHandler;
import com.qianfeng.smartplatform.security.service.MyUserDetailService;
import com.qianfeng.smartplatform.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * Created by Jackiechan on 2021/12/21/下午9:27
 *
 * @author Jackiechan
 * @version 1.0
 * @since 1.0
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true, proxyTargetClass = true)  //开启权限注解
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {

    private MyUserDetailService userDetailService;

    private BCryptPasswordEncoder bCryptPasswordEncoder;

    private MyAuthenticationFailureHandler myAuthenticationFailureHandler;


    private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;

    private MyLogoutHandler myLogoutHandler;

    private MenuService menuService;

    public void setMyLogoutHandler(MyLogoutHandler myLogoutHandler) {
        this.myLogoutHandler = myLogoutHandler;
    }

    @Autowired
    public void setUserDetailService(MyUserDetailService userDetailService) {
        this.userDetailService = userDetailService;
    }
    @Autowired
    public void setbCryptPasswordEncoder(BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }
    @Autowired
    public void setMyAuthenticationFailureHandler(MyAuthenticationFailureHandler myAuthenticationFailureHandler) {
        this.myAuthenticationFailureHandler = myAuthenticationFailureHandler;
    }
    @Autowired
    public void setMyAuthenticationSuccessHandler(MyAuthenticationSuccessHandler myAuthenticationSuccessHandler) {
        this.myAuthenticationSuccessHandler = myAuthenticationSuccessHandler;
    }

    //@Autowired
    public void setMenuService(MenuService menuService) {
        this.menuService = menuService;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
//        http.httpBasic();
//        List<Menu> allMenus = menuService.findAllMenus();
//        allMenus.forEach(menu -> {
//            if (menu.getType() != 0 && !StringUtils.hasText(menu.getPerms())) {
//
//                try {
//                    http.authorizeRequests().antMatchers(menu.getUrl()).hasAuthority(menu.getPerms());
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//
//        });
//        http.removeConfigurer(DefaultLoginPageConfigurer.class); //将默认加载的登录页配置删除
       // http.formLogin().disable();
        http.authorizeRequests()
//                .antMatchers("/layui/**", "/js/**","/websocket/*","/colorcommand/*","/humiture/*").permitAll()//放行这个地址,放行指的是到我这里了,我拦下你之后我认为你可以直接过去,然后放你过去,表面效果看起来和忽略一样
                .and().logout()
//                .logoutSuccessHandler(myLogoutHandler) //自定义退出后操作
                .logoutUrl("/logout").logoutSuccessUrl("/login").permitAll()
                .and().formLogin()
                //  .loginPage("/zidingidenglu.html")//指定自定义的登录页面
                .loginProcessingUrl("/login")//指定自定义的登录地址路径,这个路径不需要自己实际写,会由security自动处理,如果有自定义登录页面,里面的地址需要和这里一样
                // .usernameParameter("name")//自定义登录时候用户名的参数名,主要是在自定义登录页面中form表单的参数名
                //  .passwordParameter("pwd")//自定义密码参数名
                .successHandler(myAuthenticationSuccessHandler)//自定义登录成功后怎么办
                .failureHandler(myAuthenticationFailureHandler)//自定义登录失败后怎么办
                .and().authorizeRequests().anyRequest()
                .authenticated();//除了上面配置的地址之外都需要认证(登录)才可以访问,额外添加授权的以具体授权为准
             //   .permitAll();//暂时放行

    }

    /**
     * 忽略地址,忽略指的是你这些地址不归我管,我不会拦你
     *
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/js/**",
                "/css/**",
                "/users/registry",
                "/images/**",
                "/js/**",
                "/index1.html",
                "/websocket/*",
                "/colorcommand/*",
                "/humiture/*",
                "/swagger-ui.html",
                "/swagger-ui/*",
                "/swagger-resources/**",
                "/v2/api-docs",
                "/v3/api-docs",
                "/webjars/**"
        );
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailService).passwordEncoder(bCryptPasswordEncoder);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


}
